package com.dayaokeji.rhythmschoolstudent.client.home.course.task;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.chad.library.adapter.base.BaseViewHolder;
import com.dayaokeji.rhythmschoolstudent.client.common.ListFragment;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseTaskEvent;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.api.CourseTaskApi;
import com.dayaokeji.server_api.domain.CourseTask;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import retrofit2.Call;

/**
 * Created by Gorden on 2018/3/24.
 */

public class CourseTaskListFragment extends ListFragment<CourseTask,BaseViewHolder> {

    private static final String EXTRA_COURSE_ID = "course_id";

    private final CourseTaskApi courseTaskApi = ApiUtils.getApi(CourseTaskApi.class);
    private final CourseTaskAdapter courseTaskAdapter = new CourseTaskAdapter();
    private String courseId;

    public static CourseTaskListFragment newInstance(String courseId) {

        Bundle args = new Bundle();
        args.putString(EXTRA_COURSE_ID,courseId);
        CourseTaskListFragment fragment = new CourseTaskListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        courseId = getArguments().getString(EXTRA_COURSE_ID);
        setRecyclerView();
        setOnListener();
    }

    private void setRecyclerView() {
        setAdapter(courseTaskAdapter);
    }

    private void setOnListener() {
        courseTaskAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (adapter.getData().size() < position) return;
            CourseTask courseTask = (CourseTask) adapter.getData().get(position);
            courseTask.setCourseId(courseId);
            if (!getActivity().isFinishing()) {
                CourseTaskDetailActivity.navigation(getActivity(),courseTask);
            }
        });
    }

    @Override
    protected Call createCall(int offset, int max) {
        return courseTaskApi.list(courseId,offset,max);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(UpdateCourseTaskEvent updateCourseTaskEvent) {
        onRefresh();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
